<!--
  特殊访客管理组件
  创建时间：2025-09-12
  作者：开发团队
  目的：管理系统中的特殊访客信息
-->

<template>
  <div class="special-visitors">
    <el-card class="visitors-card" shadow="never">
      <template #header>
        <div class="card-header">
          <h2>特殊访客管理</h2>
          <div class="header-actions">
            <el-button
              type="primary"
              :loading="loading"
              @click="showAddDialog"
            >
              <el-icon><Plus /></el-icon>
              添加特殊访客
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 筛选器 -->
      <div class="filter-section">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-select
              v-model="filterType"
              placeholder="访客类型"
              clearable
              @change="handleFilterChange"
            >
              <el-option label="全部" value="" />
              <el-option label="VIP" value="VIP" />
              <el-option label="纠纷" value="纠纷" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-col>
          <el-col :span="18">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索姓名或手机号"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-col>
        </el-row>
      </div>
      
      <!-- 特殊访客列表 -->
      <div class="visitors-section">
        <el-table
          v-loading="loading"
          :data="paginatedVisitors"
          stripe
          class="visitors-table"
        >
          <el-table-column prop="name" label="姓名" width="120" />
          
          <el-table-column prop="phone" label="手机号" width="140" />
          
          <el-table-column prop="id_card" label="身份证号" width="180">
            <template #default="{ row }">
              {{ row.id_card || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getVisitorTypeType(row.type)">
                {{ row.type }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="valid_until" label="有效期至" width="120">
            <template #default="{ row }">
              {{ formatDate(row.valid_until) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                text
                size="small"
                @click="showEditDialog(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                text
                size="small"
                @click="deleteVisitor(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
          
          <template #empty>
            <el-empty description="暂无特殊访客数据" />
          </template>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="totalVisitors"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 添加/编辑特殊访客对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="visitorFormRef"
        :model="visitorForm"
        :rules="visitorRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="visitorForm.name" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="visitorForm.phone" />
        </el-form-item>
        
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="visitorForm.id_card" />
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-select v-model="visitorForm.type" placeholder="请选择类型">
            <el-option label="VIP" value="VIP" />
            <el-option label="纠纷" value="纠纷" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="有效期至" prop="valid_until">
          <el-date-picker
            v-model="visitorForm.valid_until"
            type="date"
            placeholder="请选择有效期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="visitorForm.remarks"
            type="textarea"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="submitVisitor"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { showError, showSuccess } from '@/utils/message'
import { formatDate } from '@/utils/date'
import type { FormInstance, FormRules } from 'element-plus'
import type { SpecialVisitor, SpecialVisitorForm } from '@/types/admin'
import { adminApi } from '@/api/admin'

// 响应式状态
const loading = ref(false)
const submitting = ref(false)
const visitors = ref<SpecialVisitor[]>([])
const filterType = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalVisitors = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEditing = ref(false)
const editingVisitorId = ref<number | null>(null)

// 表单引用
const visitorFormRef = ref<FormInstance>()

// 表单数据
const visitorForm = ref<SpecialVisitorForm>({
  name: '',
  phone: '',
  id_card: '',
  type: 'VIP',
  valid_until: '',
  remarks: ''
})

// 表单验证规则
const visitorRules: FormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 100, message: '姓名长度为1-100个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  valid_until: [
    { required: true, message: '请选择有效期', trigger: 'change' }
  ]
}

// 计算属性：过滤后的访客（不包含副作用）
const filteredVisitors = computed(() => {
  let filtered = visitors.value
  
  // 按类型筛选
  if (filterType.value) {
    filtered = filtered.filter(visitor => visitor.type === filterType.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(visitor => 
      visitor.name.toLowerCase().includes(keyword) ||
      visitor.phone.includes(keyword)
    )
  }
  
  return filtered
})

// 计算属性：分页显示的访客
const paginatedVisitors = computed(() => {
  const filtered = filteredVisitors.value
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 监听过滤结果变化，更新总记录数
watch(filteredVisitors, (newFilteredVisitors) => {
  totalVisitors.value = newFilteredVisitors.length
})

/**
 * 加载特殊访客列表
 */
const loadVisitors = async (): Promise<void> => {
  try {
    loading.value = true
    
    // 调用API获取特殊访客列表
    const response = await adminApi.getSpecialVisitors({
      page: currentPage.value,
      size: pageSize.value
    })
    visitors.value = response.items
    totalVisitors.value = response.total
  } catch (error) {
    console.error('加载特殊访客列表失败:', error)
    showError('加载特殊访客列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 显示添加对话框
 */
const showAddDialog = (): void => {
  dialogTitle.value = '添加特殊访客'
  isEditing.value = false
  editingVisitorId.value = null
  visitorForm.value = {
    name: '',
    phone: '',
    id_card: '',
    type: 'VIP',
    valid_until: '',
    remarks: ''
  }
  dialogVisible.value = true
}

/**
 * 显示编辑对话框
 * :param visitor: 特殊访客数据
 */
const showEditDialog = (visitor: SpecialVisitor): void => {
  dialogTitle.value = '编辑特殊访客'
  isEditing.value = true
  editingVisitorId.value = visitor.id
  visitorForm.value = {
    name: visitor.name,
    phone: visitor.phone,
    id_card: visitor.id_card || '',
    type: visitor.type || 'VIP',
    valid_until: visitor.valid_until,
    remarks: visitor.remarks || ''
  }
  dialogVisible.value = true
}

/**
 * 提交特殊访客表单
 */
const submitVisitor = async (): Promise<void> => {
  if (!visitorFormRef.value) return
  
  try {
    // 表单验证
    await visitorFormRef.value.validate()
    
    submitting.value = true
    
    if (isEditing.value && editingVisitorId.value) {
      // 调用API更新特殊访客
      await adminApi.updateSpecialVisitor(editingVisitorId.value, visitorForm.value)
      showSuccess('特殊访客更新成功')
    } else {
      // 调用API创建特殊访客
      await adminApi.createSpecialVisitor(visitorForm.value)
      showSuccess('特殊访客添加成功')
    }
    
    dialogVisible.value = false
    await loadVisitors()
  } catch (error) {
    console.error('提交特殊访客失败:', error)
    showError('提交特殊访客失败')
  } finally {
    submitting.value = false
  }
}

/**
 * 删除特殊访客
 * :param visitorId: 特殊访客ID
 */
const deleteVisitor = async (visitorId: number): Promise<void> => {
  try {
    // 调用API删除特殊访客
    await adminApi.deleteSpecialVisitor(visitorId)
    showSuccess(`特殊访客删除成功`)
    await loadVisitors()
  } catch (error) {
    console.error('删除特殊访客失败:', error)
    showError('删除特殊访客失败')
  }
}

/**
 * 获取访客类型标签类型
 * :param type: 访客类型
 * :return: Element Plus标签类型
 */
const getVisitorTypeType = (type: string): 'success' | 'danger' | 'warning' => {
  switch (type) {
    case 'VIP':
      return 'success'
    case '纠纷':
      return 'danger'
    default:
      return 'warning'
  }
}

/**
 * 处理筛选变化
 */
const handleFilterChange = (): void => {
  currentPage.value = 1
}

/**
 * 处理搜索
 */
const handleSearch = (): void => {
  currentPage.value = 1
}

/**
 * 处理分页大小变化
 */
const handleSizeChange = (): void => {
  currentPage.value = 1
  loadVisitors()
}

/**
 * 处理当前页变化
 */
const handleCurrentChange = (): void => {
  loadVisitors()
}

/**
 * 组件挂载时初始化数据
 */
onMounted(() => {
  loadVisitors()
})
</script>

<style scoped>
.special-visitors {
  height: 100%;
}

.visitors-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.filter-section {
  margin-bottom: 20px;
}

.visitors-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.visitors-table {
  flex: 1;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>